﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OracleClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO;
using System.Windows.Forms;
using XMLToWordLib;
using System.Runtime.InteropServices;
using DevExpress.XtraTreeList;
using PublicSelfControl;
using DevExpress.XtraEditors;
using DevExpress.Skins;
using DevExpress.XtraBars.Ribbon;
using DevExpress.Utils.Drawing;
using PublicClass;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraGrid.Localization;
using DevExpress.XtraTreeList.Localization; 
namespace XmlAppliction
{
    public partial class Form1 : DevExpress.XtraEditors.XtraForm
    {
         
        #region 共有属性
        private DataSet MenuTreeDs_catch;//树列表
        private DataSet MenuTreeDs;//树列表
        private int MenuTreeRowCount;//树列表
        private XmlAppliction.Doman.ConfigUser configUser;//配置列表
        DBLinkPool dbLinkPool = new DBLinkPool();//数据库连接集合
        ChartsFrom chartsFrom ;
        private int barTJNum = 0;//记录当前统计位置的行数

        private int DOWORKSTATUE = -1;//-1什么都没做  0加载XML统计信息  1 执行数据库统计  2已保存统计数据  3 加载已有的xml
        private bool isSSTJ = false;//是否在实时统计中
        #endregion        
        #region 初始化
        public Form1()
        {
            Localizer.Active = new ChEditLocalizer();
            GridLocalizer.Active = new ChGridLocalizer();
            TreeListLocalizer.Active = new ChTreeListLocalizer();

            this.Visible = false;
            InitializeComponent();
            initBaseSet();
            initMubanList();
            initXmlCombox();
            //皮肤列表
            InitSkinGallery();

        }

        #region 皮肤操作
        private void rgbiSkins_Gallery_ItemClick(object sender, DevExpress.XtraBars.Ribbon.GalleryItemClickEventArgs e)
        {
            DevExpress.LookAndFeel.UserLookAndFeel.Default.SetSkinStyle(e.Item.Caption);
        }
        void InitSkinGallery()
        {
            SimpleButton imageButton = new SimpleButton(); 
            foreach (SkinContainer cnt in SkinManager.Default.Skins)
            {
                imageButton.LookAndFeel.SetSkinStyle(cnt.SkinName);
                GalleryItem gItem = new GalleryItem();
                int groupIndex = 0;
                if (cnt.SkinName.Contains("Office")) groupIndex = 1;
                if (cnt.SkinName.Contains("Bonus")) groupIndex = 2;
                //if (DevExpress.DXperience.Demos.LookAndFeelMenu.IsBonusSkin(cnt.SkinName)) groupIndex = 2;
                rgbiSkins.Gallery.Groups[groupIndex].Items.Add(gItem);
                gItem.Caption = cnt.SkinName;

                gItem.Image = GetSkinImage(imageButton, 32, 17, 2);
                gItem.HoverImage = GetSkinImage(imageButton, 70, 36, 5);
                gItem.Caption = cnt.SkinName;
                gItem.Hint = cnt.SkinName;
            }
            //rgbiSkins.Gallery.Groups[1].Visible = false;
            //rgbiSkins.Gallery.Groups[2].Visible = false;
        }
        Bitmap GetSkinImage(SimpleButton button, int width, int height, int indent)
        {
            Bitmap image = new Bitmap(width, height);
            using (Graphics g = Graphics.FromImage(image))
            {
                StyleObjectInfoArgs info = new StyleObjectInfoArgs(new GraphicsCache(g));
                info.Bounds = new Rectangle(0, 0, width, height);
                button.LookAndFeel.Painter.GroupPanel.DrawObject(info);
                button.LookAndFeel.Painter.Border.DrawObject(info);
                info.Bounds = new Rectangle(indent, indent, width - indent * 2, height - indent * 2);
                button.LookAndFeel.Painter.Button.DrawObject(info);
            }
            return image;
        }
        #endregion
        void initBaseSet()
        {
            
            DateTime nowDate = DateTime.Now;
            DateTime befoDate = nowDate.AddDays(-7);  
            chartsFrom = new ChartsFrom(befoDate,nowDate);
            configUser = new XmlAppliction.Doman.ConfigUser(TJXAppliction.Program.ConfigXMLPath);
            initDefaultTable(true);
            //设置时间控件事件 
            DateTime nowdate = DateTime.Now;

            bar_SDateEdit.EditValue = nowdate.AddDays(-7); 
            bar_EDateEdit.EditValue = nowdate ;
            bar_wordDateEdit.EditValue = nowdate;
            bar_STimeEdit.EditValue = nowdate;
            bar_ETimeEdit.EditValue = nowdate;
            bar_WordTimeEdit.EditValue = nowdate;


            bar_TJPLtxt.EditValue = 10;
            bar_fontSizeSp.EditValue = 10;

            bar_CreateWordBtn.Enabled = false;
            bar_SaveTreeBtn.Enabled = false;
            //EDateEdit.DateTime = nowdate;
            //dateEdit1.DateTime = nowdate;
            //SDateEdit.DateTime = nowdate.AddDays(-7);
            
        }


        void initDefaultTable(bool reload)
        {
            string condition = ""; 
            #region 绑定数据
            if (reload)
            {
                if (MenuTreeDs != null) MenuTreeDs.Dispose();
                try
                {
                    try
                    {
                        condition = configUser.TreeCondition;

                    }
                    catch
                    {
                        condition = "";
                    }
                    MenuTreeDs = DBMgr.DbHelperOra.Query("select   lpad(t.统计项编号,length(t.统计项编号)-2 ,'0') as  ParentID,t.统计项编号 as ID, t.统计项名称,t.执行语句,t.类型,' ' as  结果,t.统计描述,t.连接参数编号,t.连接参数 from v_tj_tjx t where 1=1 " + condition + " order by t.统计项编号 asc ");

                }
                catch (Exception ex)
                {
                    MessageBox.Show(" 数据库连接失败！");
                    return;
                }
            }
            treeList1.DataSource = MenuTreeDs.Tables[0].DefaultView;
            treeList1.ExpandAll();
            MenuTreeRowCount = MenuTreeDs.Tables[0].Rows.Count;
            progressBarTjStatue.Properties.Maximum = MenuTreeRowCount;
            labelTjStatue.Text = string.Format("{0}/{1}", barTJNum, MenuTreeRowCount);
            #endregion
        }

        void initMubanList()
        {
            int index;
            string fileType = "";
            this.repositoryItemComboBox1.Items.Clear();
            DirectoryInfo dir = new DirectoryInfo(configUser.WordMubanPath );
            if (!dir.Exists)
            {
                dir.Create();
                return;
            }

            foreach (FileInfo fileinfo in dir.GetFiles())
            { 
                index=fileinfo.Name.IndexOf('.');
                fileType=fileinfo.Extension.ToLower().Trim();
                if (index < 0  ) continue;
                if( fileType == ".doc" || fileType ==".docx")
                {
                    this.repositoryItemComboBox1.Items.Add(fileinfo.Name.Substring(0, fileinfo.Name.IndexOf('.'))); 
                }
            }
            if (this.repositoryItemComboBox1.Items.Count > 0)
            {
                bar_wordMubanCombox.EditValue = repositoryItemComboBox1.Items[0].ToString();
            }
        }

        void initXmlCombox()
        {
            int index;
            string fileType = "";
            xmlCombox.Items.Clear();
            DirectoryInfo dir = new DirectoryInfo(configUser.SaveXMLPath );
            foreach (FileInfo fileinfo in dir.GetFiles())
            {
                index=fileinfo.Name.IndexOf('.');
                fileType=fileinfo.Extension.ToLower().Trim();
                if (index < 0  ) continue;
                if (fileType == ".xml" )
                {
                    xmlCombox.Items.Add(fileinfo.Name);
                }
            }
            if (xmlCombox.Items.Count > 0) xmlCombox.SelectedIndex = xmlCombox.Items.Count-1;
        
        }
        Thread tjthread;
        void initTreeMenu(string startTime,string endTime)
        {
            if (bar_searchBtn.Caption == "执 行 统 计")
            {
                setBtnEnable(false);
                btsEnableTimer.Enabled = true;
                tjthread = new Thread(new ThreadStart(BeginUpTree));
                tjthread.Start();
            }
            else
            {
                try
                {
                    setBtnEnable(true);
                    btsEnableTimer.Enabled = false;
                    tjthread.Abort();
                }
                catch (Exception ex){
                    MessageBox.Show(ex.Message);
                }
            
            }
        }

        


        /// <summary>
        /// 根据XML显示树
        /// </summary>
        /// <param name="xmlPath"></param>
        void initTreeMenu(string xmlPath)
        {
            string tempStr = "";
            if (MenuTreeDs != null)
            {
                MenuTreeDs.Dispose();
            }
            MenuTreeDs = new DataSet();
            MenuTreeDs.ReadXml(xmlPath);
            //string endTime =  EDateEdit.Text + " " + ETimeEdit.Text;
            //string startTime = SDateEdit.Text + " " + STimeEdit.Text;

            string endTime = ((DateTime)bar_EDateEdit.EditValue).ToShortDateString() + " " + ((DateTime)bar_ETimeEdit.EditValue).TimeOfDay.ToString();
            string startTime = ((DateTime)bar_SDateEdit.EditValue).ToShortDateString() + " " + ((DateTime)bar_STimeEdit.EditValue).TimeOfDay.ToString();
           
 
            MenuTreeDs.Tables[0].Columns["统计项编号"].ColumnName="ID";
            MenuTreeDs.Tables[0].Columns.Add("ParentID"); 
            foreach (DataRow row in MenuTreeDs.Tables[0].Rows)
            {
                tempStr = row["ID"].ToString();
                tempStr=tempStr.Substring(0, tempStr.Length - 2);
                row["ParentID"] = tempStr;
            } 
            treeList1.DataSource = MenuTreeDs.Tables[0].DefaultView;
            treeList1.ExpandAll();

            DataRow cfrow = MenuTreeDs.Tables[1].Rows[0];
            bar_SDateEdit.EditValue = DateTime.Parse(cfrow["统计数据开始时间"].ToString());
            bar_EDateEdit.EditValue = DateTime.Parse(cfrow["统计数据结束时间"].ToString());
            bar_wordDateEdit.EditValue = DateTime.Parse(cfrow["统计执行时间"].ToString());
            
        }

        #endregion
        #region 打开清单
        void openFrom(string tjid )
        {
            GridForm form = null;
            try
            {
                form = new GridForm(tjid, this);
                form.MdiParent = this;
                form.Show();
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message,"错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                if (form != null) form.Dispose();
            }
        }
        #endregion
        #region 通过文件打开树
        bool openXML(string file)
        {
            bool flog = false;
            string tempStr;
            DateTime sDate;
            DateTime eDate;


            if (file != "" && file.Substring(file.Length - 3).ToLower() == "xml")
            {
                initTreeMenu(file);
                configUser.LastsaveXMLPath  = file;

                DataRow row = MenuTreeDs.Tables[1].Rows[0];
                tempStr = row["统计数据开始时间"].ToString(); 
                sDate = DateTime.Parse(row["统计数据开始时间"].ToString());
                eDate = DateTime.Parse(row["统计数据结束时间"].ToString()); 

                bar_SDateEdit.EditValue = sDate;
                bar_STimeEdit.EditValue = sDate;
                bar_EDateEdit.EditValue = eDate;
                bar_ETimeEdit.EditValue = eDate;
                flog = true;
            }
            return flog;
        }
        #endregion
        #region 导出xml
        string WriteXML()
        {
           return  WriteXML( "","");
        }
        string WriteXML(string foldPath,string fileName)
        {

            
            string msg = "成功保存！";
            string fold = configUser.SaveXMLPath.Trim();
            if (foldPath != "") fold = foldPath;

            string endTime = ((DateTime)bar_EDateEdit.EditValue).ToShortDateString() + " " + ((DateTime)bar_ETimeEdit.EditValue).TimeOfDay.ToString();
            string startTime = ((DateTime)bar_SDateEdit.EditValue).ToShortDateString() + " " + ((DateTime)bar_STimeEdit.EditValue).TimeOfDay.ToString();

            string dotime = ((DateTime)bar_wordDateEdit.EditValue).ToShortDateString() + " " + ((DateTime)bar_WordTimeEdit.EditValue).TimeOfDay.ToString(); 
            string filepath = string.Format("{0}\\({1})开始({2})结束.xml", fold, startTime.Replace(":", ""), endTime.Replace(":", ""), DateTime.Now.Millisecond);
            if (fileName != "") filepath = fileName;
            try
            {
                XMLHelper.writeXML(MenuTreeDs, fold, startTime, endTime,dotime, filepath);
                xmlCombox.Items.Add(filepath.Substring(filepath.LastIndexOf('\\') + 1));
                xmlCombox.SelectedIndex = xmlCombox.Items.Count - 1;
            }
            catch(Exception ex)
            {
                msg = "请先执行统计！";
            }
            return msg;

        }
        #endregion
        #region 事件操作
        private void SDateEdit_EditValueChanged(object sender, EventArgs e)
        {
            DateTime sdate = (DateTime)bar_SDateEdit.EditValue;
            DateTime edate = (DateTime)bar_EDateEdit.EditValue;
            if (sdate.Year < 1900 || edate.Year < 1900) return;
            int days = (sdate - edate).Days;
            if (days > 0)
            {
                MessageBox.Show("起始日期必须小于结束日期！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                bar_SDateEdit.EditValue = bar_EDateEdit.EditValue;
            }
            tjNumResate();
        }

        private void EDateEdit_EditValueChanged(object sender, EventArgs e)
        {
            DateTime sdate = (DateTime)bar_SDateEdit.EditValue;
            DateTime edate = (DateTime)bar_EDateEdit.EditValue;
            if (sdate.Year < 1900 || edate.Year < 1900) return;
            int days = (edate - sdate).Days;
            if (days < 0)
            {
                MessageBox.Show("结束日期必须大于起始日期！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                bar_EDateEdit.EditValue = bar_SDateEdit.EditValue;
            }
            tjNumResate();
        }
        private void treeList1_DoubleClick(object sender, EventArgs e)
        {
            string nodeJG; 
            DevExpress.XtraTreeList.Nodes.TreeListNode node = treeList1.FocusedNode;
            if (node == null) return;
            nodeJG=node.GetValue("结果").ToString();
            if ( nodeJG ==null ||  nodeJG.Trim() == "")
            {
                MessageBox.Show("无查看结果!");
                return;
            }
            if (nodeJG != "-1" && nodeJG != "")
            {
                if (Convert.ToInt32(nodeJG) > 30000)
                {
                    MessageBox.Show("一次查看数据量过大，无权查看！");
                    return;
                }
                openFrom(node.GetValue("ID").ToString());
            }
        }


        private void bar_searchBtn_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        { 
            try
            { 
                //如果是加载以前的XML文件 则重新初始化表
                if (this.DOWORKSTATUE == 3 && !isSSTJ)
                {
                    initDefaultTable(true);
                }

                ShowTree(); 
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            //(xtraTabbedMdiManager1.SelectedPage.MdiChild as GridForm).UpGrid();
        }

        void ShowTree()
        {
            string endTime = ((DateTime)bar_EDateEdit.EditValue).ToShortDateString() + " " + ((DateTime)bar_ETimeEdit.EditValue).TimeOfDay.ToString();
            string startTime = ((DateTime)bar_SDateEdit.EditValue).ToShortDateString() + " " + ((DateTime)bar_STimeEdit.EditValue).TimeOfDay.ToString(); 
            initTreeMenu(startTime, endTime); 
        }

        private void barButtonItem3_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        { 
            MessageBox.Show(WriteXML()); 
        }



        
        private void barButtonItem2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            bar_SSTJbtn_ItemClick(sender, e);
        }
        private void bar_CreateWordBtn_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        { 
            //如果 模板列表，xml列表为空


            string mubanName = this.bar_wordMubanCombox.EditValue.ToString();
            if (mubanName == "")
            {
                MessageBox.Show("请选择WORD模板！");
                return;
            }
            if (xmlCombox.Text == "")
            {
                MessageBox.Show("请选择统计项XML模板！");
                return;
            }
            try
            {

                string tmp_path = string.Format("{0}{1}_执行时间：{2}年{3}月{4}日{5}点{6}分{7}秒.doc", configUser.SaveWordPath.Trim(), mubanName, DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
                string mubanpath = string.Format("{0}\\{1}.doc", configUser.WordMubanPath.Trim(), mubanName);
                string lastXMLPath = configUser.LastsaveXMLPath.Trim();
                
                XMLToWordLib.MakeWordLib.TagReplaceToWord(lastXMLPath, mubanpath, tmp_path);
               // xtraUserWordControl1.LoadWord(tmp_path);  
               openWordView(tmp_path);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message,"错误",  MessageBoxButtons.OK,  MessageBoxIcon.Error);
            }
        }


        void openWordView(string filname)
        {
            int sindex = filname.LastIndexOf('\\') + 1;
            int eindex = filname.LastIndexOf('.');
            string name = filname.Substring(sindex, eindex - sindex);
            Form form = new Form();
            form.Text = name;
            form.Name = name;
            form.MdiParent = this;
            form.Show();

            XtraUserWordControl xtraUserWordControl = new XtraUserWordControl();
            xtraUserWordControl.LoadWord(filname);
            xtraUserWordControl.Dock = DockStyle.Fill;

            form.Controls.Add(xtraUserWordControl);
        
        }

        private void bar_SaveTreeBtn_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        { 
            string msg="保存失败！";
            int tempIndex=0;
            saveFileDialog1.Filter = "xml文件|*.xml";
            DialogResult showDialog = saveFileDialog1.ShowDialog(this);

            if (showDialog == DialogResult.OK)
            {
                if (File.Exists(saveFileDialog1.FileName))
                {
                    File.Delete(saveFileDialog1.FileName);
                }

                tempIndex=saveFileDialog1.FileName.LastIndexOf('\\')-1;
                msg=WriteXML(saveFileDialog1.FileName.Substring(0, tempIndex), saveFileDialog1.FileName); 
            }
            if (msg == "成功保存！")
            {
                configUser.LastsaveXMLPath  = saveFileDialog1.FileName;
                DOWORKSTATUE =  2;
                bar_CreateWordBtn.Enabled = true;
            }
            MessageBox.Show(msg); 
        }
        private void bar_importXmlBtn_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        { 
            try
            {
                DialogResult showDialog = openFileDialog1.ShowDialog();
                openFileDialog1.Filter = "xml文件|*.xml";
                if (showDialog == DialogResult.OK)
                {
                    if (openXML(openFileDialog1.FileName))
                    {
                        closeAllFrom();
                        bar_SaveTreeBtn.Enabled = false;
                        bar_CreateWordBtn.Enabled = true;
                        this.DOWORKSTATUE = 3;
                        configUser.LastsaveXMLPath = openFileDialog1.FileName;
                        MessageBox.Show("导入统计成功！", "成功");
                    }
                    else
                    {
                        MessageBox.Show("请选择正确的统计记录文件！","提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); ;
                    }
                }
            }
            catch
            {
                MessageBox.Show("请选择正确的统计记录文件！","提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); ;
            }
        }


        void closeAllFrom()
        {
            foreach (Form form in this.MdiChildren)
            {
                if (form != chartsFrom) form.Dispose();
            }
        }

        

        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }


        private void bar_openYYTJ_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            System.Diagnostics.Process.Start("explorer.exe", configUser.SaveXMLPath);
        }

        private void bar_OpenBGML_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        { 
            System.Diagnostics.Process.Start("explorer.exe", configUser.SaveWordPath );
        }

        private void simpleButton5_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("explorer.exe", configUser.WordMubanPath );
        }
 
        

        private void treeList1_MouseDown(object sender, MouseEventArgs e)
        {
            Point p = new Point(Cursor.Position.X, Cursor.Position.Y);
            if (e.Button == MouseButtons.Right)
            {
                treeList1.ContextMenuStrip = null;
                TreeListHitInfo hinfo = treeList1.CalcHitInfo(new Point(e.X, e.Y));
                DevExpress.XtraTreeList.Nodes.TreeListNode node = hinfo.Node;
                treeList1.FocusedNode = node;
                if (node != null)
                { 
                    TreePopupMenu.ShowPopup(p);
                }
            
            }
        }

       

       
        #endregion
        #region 树右键菜单

        private void barbtnShowNumCol_CheckedChanged(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            DevExpress.XtraBars.BarCheckItem checkeder = (sender as DevExpress.XtraBars.BarCheckItem);

            if (!checkeder.Checked)
            {
                checkeder.Caption = "打开编号列";
                treCol统计项编号.Visible = false;
            }
            else
            {
                treCol统计项编号.Visible = true;
                checkeder.Caption = "关闭编号列";
            }
        }

       

        private void treeList1_MouseEnter(object sender, EventArgs e)
        {
            treeList1.VertScrollVisibility = ScrollVisibility.Auto;
            treeList1.HorzScrollVisibility = ScrollVisibility.Auto;
        }

        private void treeList1_MouseLeave(object sender, EventArgs e)
        {
            treeList1.VertScrollVisibility = ScrollVisibility.Never;
            treeList1.HorzScrollVisibility = ScrollVisibility.Never;
        }

        private void PopExpAll_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

            if (PopExpAll.Caption == "全部折叠")
            {
                PopExpAll.Caption = "全部展开";
                treeList1.CollapseAll();
            }
            else
            {
                treeList1.ExpandAll();
                PopExpAll.Caption = "全部折叠";
            }
        }

        private void barLookList_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            treeList1_DoubleClick(sender, e);
        }
        #endregion
        #region 显示帮助窗口

        private void bar_helpBtn_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        { 
            (new helpFrom()).ShowDialog(this);
        }

        #endregion
        #region 杂

        private void bar_SetBtn_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
 
            configUser.saveConfigXML();
            configSetFrom tempfrom = new configSetFrom();
            tempfrom.ShowDialog(this);
            configUser = new XmlAppliction.Doman.ConfigUser(TJXAppliction.Program.ConfigXMLPath); 
            //刷新列表
            initMubanList();
            initXmlCombox();
        }
        private void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
             //lpad(t.统计项编号,length(t.统计项编号)-2 ,'0') as  ParentID,t.统计项编号 as ID, t.统计项名称,t.执行语句,t.类型,t.结果,t.统计描述,t.连接参数编号,t.连接参数 from v_tj_tjx t where 1=

            DevExpress.XtraTreeList.Nodes.TreeListNode node = treeList1.FocusedNode;
            if (node == null) return;
            string tjid = node.GetValue("ID").ToString();
            string nodeJG = node.GetValue("结果").ToString();
            if (nodeJG != "-1" && nodeJG != "")
            { 
                //chartsFrom.MdiParent = this;
                string endTime = ((DateTime)bar_EDateEdit.EditValue).ToShortDateString() + " " + ((DateTime)bar_ETimeEdit.EditValue).TimeOfDay.ToString();
                string startTime = ((DateTime)bar_SDateEdit.EditValue).ToShortDateString() + " " + ((DateTime)bar_STimeEdit.EditValue).TimeOfDay.ToString();
           
                    try
                    { 
                        if (!chartsFrom.Visible)
                        {
                            chartsFrom.Show();
                        }
                    }
                    catch
                    {
                        chartsFrom = new ChartsFrom(DateTime.Parse( startTime), DateTime.Parse(endTime));
                        //chartsFrom.MdiParent = this;
                        chartsFrom.Show();
                    }

                    chartsFrom.TopMost = true;
                    try
                    {
                        chartsFrom.chartsShow.AddSerie(tjid);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "程序配置错误！", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
            }
        }

        private void barButtonItem2_ItemClick_1(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            DevExpress.XtraTreeList.Nodes.TreeListNode node = treeList1.FocusedNode;
            node.ExpandAll();
        }


        private void barButtonItem5_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            string endTime = ((DateTime)bar_EDateEdit.EditValue).ToShortDateString() + " " + ((DateTime)bar_ETimeEdit.EditValue).TimeOfDay.ToString();
            string startTime = ((DateTime)bar_SDateEdit.EditValue).ToShortDateString() + " " + ((DateTime)bar_STimeEdit.EditValue).TimeOfDay.ToString();
           
            try
            {
                if (!chartsFrom.Visible)
                {
                    chartsFrom.Show();
                }
            }
            catch
            {
                chartsFrom = new ChartsFrom( DateTime.Parse( startTime),  DateTime.Parse( endTime)); 
                chartsFrom.Show();
            }
        }
        #endregion
        #region 当统计过程中的操作
        private void btsEnableTimer_Tick(object sender, EventArgs e)
        { 
            //如果在统计过程中 则什么都不做
            if (!IsTongJi)//统计完成
            {
                setBtnEnable(true);
                btsEnableTimer.Enabled = false;
                
            } 
            progressBarTjStatue.Position  =  barTJNum;
            labelTjStatue.Text = string.Format("{0}/{1}", barTJNum, MenuTreeRowCount); 

        }

        void setBtnEnable(bool flog)
        { 
                if (!flog )
                {
                    this.Text += "( 统计中... )";
                    bar_SaveTreeBtn.Enabled = false;
                }
                else
                {
                    int indexNum = this.Text.IndexOf('(');
                    if (indexNum < 0) indexNum = this.Text.Length;
                    this.Text = this.Text.Substring(0, indexNum);
                } 
            StatuePanel.Visible = !flog;
            //this.ControlBox = flog;//关闭按钮

            if (DOWORKSTATUE > 1 && flog)
            {
                bar_CreateWordBtn.Enabled = true;
            }
            else
            { 
                bar_CreateWordBtn.Enabled = false;
            }
            bar_SaveTreeBtn.Enabled = flog;

            //this.UpBtnsPanel.Enabled = flog;//更新按钮
            bar_SDateEdit.Enabled = flog;
            bar_EDateEdit.Enabled = flog;
            bar_wordDateEdit.Enabled = flog;
            bar_STimeEdit.Enabled = flog;
            bar_ETimeEdit.Enabled = flog;
            bar_WordTimeEdit.Enabled = flog;
            //SaveTreeBtn.Enabled = flog;
            bar_searchBtn.Caption = flog ? "执 行 统 计" : "取 消 统 计";

            if (barTJNum >= MenuTreeRowCount && flog)
            {
                this.bar_SaveTreeBtn.Enabled = true;
                //正常统计完成
                barTJNum = 0;
            }
            this.bar_SSTJbtn.Enabled = flog;
        }
        #endregion
        #region  窗口最小化，最大化， 关闭几个按钮事件
        private void closeBtn_Click(object sender, EventArgs e)
        {
            this.Close(); 
        }

        private void Btn_MouseEnter(object sender, EventArgs e)
        {

            PictureBox img = (sender as PictureBox);
            img.BorderStyle = BorderStyle.FixedSingle;
        }

        private void Btn_MouseLive(object sender, EventArgs e)
        {

            PictureBox img = (sender as PictureBox);
            img.BorderStyle = BorderStyle.None;
        }

        private void minBtn_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }

        private void maxminBtn_Click(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Maximized)
            {
                this.WindowState = FormWindowState.Normal;
            }
            else
            {
                this.WindowState = FormWindowState.Maximized;
            }
        }
        #endregion
        #region 多线程 统计数据

        bool IsTongJi = false;
        void BeginUpTree()
        {
            if (!isSSTJ) DOWORKSTATUE = 1;//如果不是实时统计
            try
            {
                IsTongJi = true;
                string endTime = ((DateTime)bar_EDateEdit.EditValue).ToShortDateString() + " " + ((DateTime)bar_ETimeEdit.EditValue).TimeOfDay.ToString();
                string startTime = ((DateTime)bar_SDateEdit.EditValue).ToShortDateString() + " " + ((DateTime)bar_STimeEdit.EditValue).TimeOfDay.ToString();
           
                DBLinkUser dbLinkUser = null;
                string linkUserID;
                string sql = "";
                int count=MenuTreeDs.Tables[0].Rows.Count;
                //foreach (DataRow dtrow in MenuTreeDs.Tables[0].Rows)
                for ( ;barTJNum<count;barTJNum++)
                {
                    DataRow dtrow = MenuTreeDs.Tables[0].Rows[barTJNum];
                    dtrow["结果"] = "统计中...";
                    //-------查询出统计数据
                    if (dtrow["执行语句"].ToString().Length > 10)
                    {
                        try
                        {
                            linkUserID = dtrow["连接参数编号"].ToString();
                            dbLinkPool.Add(linkUserID, linkUserID, dtrow["连接参数"].ToString());
                            //dbLinkPool.Add(linkUserID, linkUserID, DBMgr.DbHelperOra.connectionString);//调试
                            dbLinkUser = dbLinkPool.GetLinkUser(linkUserID);
                            //连接数据库
                            dbLinkUser.Start();
                            sql = string.Format(dtrow["执行语句"].ToString(), startTime, endTime);
                            dtrow["结果"] = dbLinkUser.GetTJNum(sql);
                        }
                        catch
                        {
                            dtrow["结果"] = -1;
                        }
                    }
                    else
                    {
                        dtrow["结果"] = "";
                    } 
                }

                //Thread.Sleep(5000);
                IsTongJi = false;

            }
            catch 
            {
                DOWORKSTATUE = -1;
                //MessageBox.Show("多线程统计结果出现错误！"+ex.Message);
                barTJNum--;
            }

            
        }

        #endregion

        private void barBtnTJChilds_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            DevExpress.XtraTreeList.Nodes.TreeListNode node = treeList1.FocusedNode;
            if (node == null) return;
            string tjid = node.GetValue("ID").ToString();
            string nodeJG = node.GetValue("结果").ToString();
            if (nodeJG != "-1"  )
            {
                string endTime = ((DateTime)bar_EDateEdit.EditValue).ToShortDateString() + " " + ((DateTime)bar_ETimeEdit.EditValue).TimeOfDay.ToString();
                string startTime = ((DateTime)bar_SDateEdit.EditValue).ToShortDateString() + " " + ((DateTime)bar_STimeEdit.EditValue).TimeOfDay.ToString(); 
                //新建窗口进行统计
                NodeTreeTJFrom tjfros = new NodeTreeTJFrom();
                tjfros.Show();
                tjfros.devControlTreeList1.DataBind(tjid, startTime, endTime);
            }
        }

        #region 实时统计

        private void EditTjResetNum_EditValueChanged(object sender, EventArgs e)
        {
            tjNumResate();
        }

        void tjNumResate()
        {
            for (int i = 0; i <= barTJNum && i < MenuTreeRowCount; i++) 
            { 
                MenuTreeDs.Tables[0].Rows[i]["结果"]=""; 
            }
            barTJNum = 0;
        }

        private void txtTJPL_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                double.Parse(bar_TJPLtxt.EditValue.ToString());
            }
            catch
            {
                bar_TJPLtxt.EditValue = 1;//默认为一分钟刷新一次
            }
        }


        private void bar_SSTJbtn_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
 
            if (IsTongJi) return;
            if (bar_SSTJbtn.Caption == "启动定时监视")
            {
                MenuTreeDs_catch = MenuTreeDs; 
                if (initSSTJTable())
                {
                    isSSTJ = true;
                    bar_SSTJbtn.Caption = "停止定时监视";
                    this.bar_SSTJbtn.Glyph = global::XmlAppliction.Properties.Resources._13;
                    bar_SSTJbtn.Appearance.ForeColor = Color.Red;
                    bar_SSTJbtn.Enabled = false;
                    timerSSTJ.Start();
                }
            }
            else
            {
                
                isSSTJ = false;
                MenuTreeDs = MenuTreeDs_catch;
                timerSSTJ.Stop();
                timerSSTJ.Interval = 1;
                initDefaultTable(false);
                bar_SSTJbtn.Caption = "启动定时监视";
                this.bar_SSTJbtn.Glyph = global::XmlAppliction.Properties.Resources._5;
                bar_SSTJbtn.Appearance.ForeColor = Color.Black;
                bar_SSTJbtn.Enabled = true;

                if (this.DOWORKSTATUE > 1)
                {
                    bar_CreateWordBtn.Enabled = true;
                }
            }

            //设置相关按钮状态
            bar_importXmlBtn.Enabled = !isSSTJ;

        }
        void setSSTJ_BtnsEnable()
        { 
        
        }


        bool initSSTJTable()
        {
            string sstjcondition = configUser.SSTJCondition;
            if (sstjcondition == "")
            {
                MessageBox.Show("请输入实时统计条件！");
                return false;
            }
            #region 绑定数据
            if (MenuTreeDs != null) MenuTreeDs.Dispose();
            try
            {

                MenuTreeDs = DBMgr.DbHelperOra.Query("select   lpad(t.统计项编号,length(t.统计项编号)-2 ,'0') as  ParentID,t.统计项编号 as ID, t.统计项名称,t.执行语句,t.类型,' ' as  结果,t.统计描述,t.连接参数编号,t.连接参数 from v_tj_tjx t where 1=1 " + sstjcondition + " order by t.统计项编号 asc "); 

            }
            catch (Exception ex)
            {
                MessageBox.Show(" 实时统计条件配置错误！");
                return false;
            }
            treeList1.DataSource = MenuTreeDs.Tables[0].DefaultView;
            treeList1.ExpandAll();
            MenuTreeRowCount = MenuTreeDs.Tables[0].Rows.Count;
            progressBarTjStatue.Properties.Maximum = MenuTreeRowCount;
            barTJNum = 0;
            labelTjStatue.Text = string.Format("{0}/{1}", barTJNum, MenuTreeRowCount); 
            #endregion

            return true;
        }

        private void timerSSTJ_Tick(object sender, EventArgs e)
        {
            //如果不在统计过程中则开始统计
            if (!IsTongJi)
            {
                bar_searchBtn_ItemClick(null, null);
                bar_lbLastUpTime.Caption = string.Format("最后更新时间：{0}", DateTime.Now.ToString());
                timerSSTJ.Interval = (int)(double.Parse(bar_TJPLtxt.EditValue.ToString()) * 60 * 1000);
            }
            else {

                bar_SSTJbtn_ItemClick(null, null);
            }
        }

        #endregion

         

        private void bar_SSTJUpbtn_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (bar_SSTJbtn.Caption == "停止定时监视")
            {
                bar_searchBtn_ItemClick(null, null);
                bar_lbLastUpTime.Caption = string.Format("最后更新时间：{0}", DateTime.Now.ToString());
            }
        }

       
  
       

       

    }
}
